package com.powernode.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.powernode.business.domain.Attachment;
import com.powernode.business.domain.Car;
import com.powernode.business.dto.CarDto;
import com.powernode.business.mapper.AttachmentMapper;
import com.powernode.business.mapper.CarMapper;
import com.powernode.business.service.CarService;
import com.powernode.common.core.domain.entity.SysDept;
import com.powernode.common.core.domain.model.LoginUser;
import com.powernode.system.mapper.SysDeptMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CarServiceImpl implements CarService {

    @Resource
    private CarMapper carMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return 0;
    }

    @Override
    public int insert(Car record) {
        return carMapper.insert(record);
    }

    @Override
    public int insertSelective(Car record) {
        return carMapper.insertSelective(record);
    }

    @Override
    public Car selectByPrimaryKey(Integer id) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(Car record) {
        return carMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Car record) {
        return carMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Car> selectCarList(Car car, LoginUser loginUser) {
        return carMapper.selectCarList(car, loginUser);
    }

    /**
     * 新增车辆
     * @param carDto
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int addCar(CarDto carDto, LoginUser loginUser) {
        log.info("新增车辆{},当前用户id为{}", JSON.toJSONString(carDto),loginUser.getUserId());
        //先判断车牌号是否存在
        String carNumber = carDto.getCarNumber();
        //查询一下判断
        Car car = carMapper.selectCarByCarNum(carNumber);
        if (!ObjectUtils.isEmpty(car)){
            //条件判断if中如果查询不为空则条件成立，代表此车已经存在
            throw new IllegalArgumentException("车辆已经存在，请勿重复添加");
        }
        String username = loginUser.getUsername();
        //如果每次去一下会导致多次方法进栈
        carDto.setCreateBy(username);
        carDto.setUpdateBy(username);
        carDto.setCreateTime(new Date());
        carDto.setUpdateTime(new Date());
        Long deptId = carDto.getDeptId();
        //查询部门
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        carDto.setDeptName(sysDept.getDeptName());
        carDto.setDelFlag("0");
        //插入汽车表
        int i = carMapper.insert(carDto);
        if (i > 0){
            //处理图片
            handleImg(carDto, username);
        }
        return i;
    }

    private void handleImg(CarDto carDto, String username) {
        String carImgs = carDto.getCarImgs();
        if (StringUtils.hasText(carImgs)){
            //有图片
            String[] imgs = null;
            //判断有没有多个图片，逗号分割
            if (carImgs.contains(",")){
                imgs = carImgs.split(",");
                //循环图片数组，创建对象，插入数据库
            }else {
                imgs = new String[]{carImgs};
            }
            //统一操作
            ArrayList<Attachment> attachments = new ArrayList<>();
            for (String img : imgs) {
                //处理名字
                String fileName = img.substring(img.lastIndexOf("/") + 1);
                String extType = StringUtils.getFilenameExtension(img);
                //构建者模式,链式编程
                Attachment attachment = Attachment.builder()
                        .fileName(fileName)
                        .fileType(extType)
                        .filePath(img)
                        .carNumber(carDto.getCarNumber())
                        .delFlag("0")
                        .createBy(username)
                        .updateBy(username)
                        .createTime(new Date())
                        .updateTime(new Date())
                        .build();
                //插入数据库
                attachments.add(attachment);
            }
            //统一插入数据库
            attachmentMapper.saveBatch(attachments);
        }
    }


    /**
     * 修改之前回显数据
     * @param id
     * @return
     */
    @Override
    public CarDto getCarInfo(Integer id) {
        CarDto carDto = new CarDto();
        //根据id查询车辆
        Car car = carMapper.selectByPrimaryKey(id);
        //查图片
        List<String> imgs = attachmentMapper.selectImgByCarNum(car.getCarNumber());
        //填充对象
        String carImgs = String.join(",", imgs);
        carDto.setCarImgs(carImgs);
        //对象拷贝，只要属性名相同，就可以直接拷贝
        BeanUtils.copyProperties(car,carDto);
        return carDto;
    }

    /**
     * 修改车辆数据
     * @param carDto
     * @param loginUser
     * @return
     */
    @Override
    //开启事务防止多人修改时
    @Transactional(rollbackFor = RuntimeException.class)
    public int updateCar(CarDto carDto, LoginUser loginUser) {
        log.info("修改车辆{},当前用户为{}",JSON.toJSONString(carDto),loginUser.getUserId());
        String username = loginUser.getUsername();
        carDto.setUpdateBy(username);
        carDto.setUpdateTime(new Date());
        Long deptId = carDto.getDeptId();
        //查询部门
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        carDto.setDeptName(sysDept.getDeptName());
        //更新数据
        int i = carMapper.updateByPrimaryKeySelective(carDto);
        if (i > 0){
            //处理图片
            //1.将之前的图片删掉
            attachmentMapper.delImg(carDto.getCarNumber());
            //2.插入新的图片
            handleImg(carDto,username);
        }
        return i;
    }

    /**
     * 删除车辆信息
     * @param ids
     * @param loginUser
     * @return
     */
    @Override
    public int deleteCar(List<Integer> ids, LoginUser loginUser) {
        log.info("删除客户的ids为{}，当前用户的id是",ids.toString(),loginUser.getUserId());
        String username = loginUser.getUsername();
        //1.先把需要删除的车辆查出来
        List<Car> carList = carMapper.selectCarById(ids);
        //2.判断是否为空
        if (CollectionUtils.isEmpty(carList)){
            return 0;
        }
        //判断车辆是否出租，循环过滤，判断已出租的车辆
        List<Car> rentCarList = carList.stream()
                .filter(car -> car.getStatus().equals(1))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(rentCarList)){
            throw new IllegalArgumentException("车辆正在出租，不能删除");
        }
        //执行到这里就代表可以删除
        int i = carMapper.delCarBatch(ids,username);
        if (i > 0){
            //处理图片
            List<String> carNums = carList.stream()
                    .map(Car::getCarNumber)
                    .collect(Collectors.toList());
            attachmentMapper.delImgBatch(carNums,username);
        }
        return i;
    }
}

